<template>
  <div>
    <el-card>
      <div class="flex justify-between items-center mb-4">
        <el-button type="primary" @click="openForm()">新增作品</el-button>
      </div>
      <el-table :data="products" style="width: 100%">
        <el-table-column label="标题" prop="title" />
        <el-table-column label="分类">
          <template #default="{ row }">
            {{ getCategoryName(row.category_id) }}
          </template>
        </el-table-column>
        <el-table-column label="价格" prop="price" />
        <el-table-column label="技术栈">
          <template #default="{ row }">
            <el-tag v-for="tech in row.tech_stack_ids" :key="tech" class="mr-1">{{ getTechName(tech) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="openForm(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteProduct(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <ProductForm
      v-model="formVisible"
      :product="editingProduct"
      @success="fetchProducts"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getProducts, deleteProductById } from '@/api/products'
import { useProductStore } from '@/stores/product'
import ProductForm from './ProductForm.vue'

const productStore = useProductStore();
const products = ref([])
const formVisible = ref(false)
const editingProduct = ref(null)

const fetchProducts = async () => {
  const { data: { list }} = await getProducts()
  products.value = list
}

const openForm = (product = null) => {
  console.log('点击了打开')
  editingProduct.value = product
  formVisible.value = true
}

const deleteProduct = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除此作品吗？', '警告', { type: 'warning' })
    await deleteProductById(id)
    ElMessage.success('删除成功')
    fetchProducts()
  } catch {}
}

const getCategoryName = (categoryId) => {
  return productStore.categores.find(item => item.id == categoryId)?.name
}

const getTechName = (techId) => {
  return productStore.techStacks.find(item => item.id == techId)?.name
}
onMounted(async () => {
  await fetchProducts();
  await productStore.init();
})
</script>
